import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Preset } from './schemas/preset.schema';
import { CreatePresetDto, UpdatePresetDto } from './dto/preset.dto';
import { PRESET_CATEGORIES, BASE_PRESETS } from './preset.config';

@Injectable()
export class PresetService {
  constructor(
    @InjectModel(Preset.name) private presetModel: Model<Preset>
  ) {
    this.initializePresets();
  }

  // 初始化预设数据
  private async initializePresets() {
    const count = await this.presetModel.countDocuments();
    if (count === 0) {
      await this.presetModel.insertMany(BASE_PRESETS);
    }
  }

  // 获取预设分类
  getCategories() {
    return PRESET_CATEGORIES;
  }

  // 获取预设列表
  async getPresets(filter: {
    category?: string;
    template_type?: string;
    tags?: string[];
  }) {
    const query: any = { is_deleted: false };
    
    if (filter.category) {
      query.category = filter.category;
    }
    
    if (filter.template_type) {
      query.template_type = filter.template_type;
    }
    
    if (filter.tags?.length) {
      query.tags = { $in: filter.tags };
    }

    return this.presetModel
      .find(query)
      .sort({ created_at: -1 })
      .exec();
  }

  // 获取预设详情
  async getPreset(id: string) {
    return this.presetModel.findById(id).exec();
  }

  // 创建自定义预设
  async createPreset(createPresetDto: CreatePresetDto) {
    const preset = new this.presetModel({
      ...createPresetDto,
      created_at: new Date(),
      updated_at: new Date()
    });
    return preset.save();
  }

  // 更新预设
  async updatePreset(id: string, updatePresetDto: UpdatePresetDto) {
    return this.presetModel
      .findByIdAndUpdate(
        id,
        { ...updatePresetDto, updated_at: new Date() },
        { new: true }
      )
      .exec();
  }

  // 删除预设
  async deletePreset(id: string) {
    return this.presetModel
      .findByIdAndUpdate(id, { is_deleted: true, updated_at: new Date() })
      .exec();
  }

  // 应用预设到参数
  applyPreset(params: Record<string, any>, preset: Preset): Record<string, any> {
    return {
      ...params,
      ...preset.params
    };
  }
} 